﻿using BlogApi.Data;
using BlogApi.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlogApi.Services
{
    public class LikeRepository:ILikeRepository
    {
        private readonly BlogDbContext _context;

        public LikeRepository(BlogDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }
        public async Task<IEnumerable<Like>> GetLikesAsync()
        {
            return await _context.Likes_table.ToListAsync();
        }
        public async Task<IEnumerable<Like>> GetLikesByUserIdAsync(Guid userId)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(userId));
            }
            return await _context.Likes_table.Where(like => like.UserId == userId).ToListAsync();
        }
        public async Task<Like> GetLikeAsync(Guid likeId)
        {
            if (likeId == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(likeId));
            }
            return await _context.Likes_table.FirstOrDefaultAsync(like => like.Id == likeId);
        }
        public async Task<Like> GetLikeAsync(Guid articleId, Guid userId)
        {
            return await _context.Likes_table.FirstOrDefaultAsync(like => like.ArticleId == articleId && like.UserId == userId);
        }
        public void AddLike(Like like)
        {
            if (like == null)
            {
                throw new ArgumentNullException(nameof(like));
            }
            _context.Likes_table.Add(like);
        }
        public void UpdateLike(Like like)
        {
            //由于数据库上下文会对实体进行跟踪 所以这句话可以不写
            //_context.Entry(like).State = EntityState.Modified;
        }
        public void DeleteLike(Like like)
        {
            if (like == null)
            {
                throw new ArgumentNullException(nameof(like));
            }
            _context.Likes_table.Remove(like);
        }
        public async Task<bool> LikeExistsAsync(Guid likeId)
        {
            if (likeId == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(likeId));
            }
            return await _context.Likes_table.AnyAsync(like => like.Id == likeId);
        }
        public async Task<bool> UserLikeArticleExistsAsync(Guid articleId, Guid userId)
        {
            return await _context.Likes_table.AnyAsync(like => like.ArticleId == articleId && like.UserId == userId);
        }
        public async Task<bool> SaveAsync()
        {
            return await _context.SaveChangesAsync() >= 0;
        }
    }
}
